package com.itzhoun.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itzhoun.entity.UserEntity;
import com.itzhoun.model.HelloApplicationEvent;
import com.itzhoun.model.WatchApplicationEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 采用注解的方式 异步执行
 * 采用注解的方式很简单 一个事件、一个发布、一个监听
 * @author 周楠
 * @Date 2022/11/02/下午 1:16
 */
@Component
@Slf4j
public class BaseListener<T> {

    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK, classes = HelloApplicationEvent.class)
    public void helloNotified(HelloApplicationEvent event) {
        log.info("你好事件开始执行");
        try {
            Thread.sleep(3000);
            UserEntity userEntity = JSONUtil.toBean(event.getSource().toString(), UserEntity.class);
            log.info("我的名字:{}, 年龄:{}", userEntity.getUsername(), userEntity.getAge());
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        log.info("message:{}", event.getSource());

    }

    @Async
    @EventListener(classes = WatchApplicationEvent.class)
    public void watchNotified(WatchApplicationEvent event) {
        log.info("watch事件执行");
        try {
            Thread.sleep(5000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        log.info("watch事件结束");

    }
}
